import DEL_ICON from '@/assets/image/del_sm.png';
import DOC_ICON from '@/assets/image/doc.png';

import { upload_files } from '@/services/ant-design-pro/miniModel1';
import { FileAddOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import type { UploadProps } from 'antd';
import { Button, message, Modal, Upload } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import './index.less';
const MiniModel1: React.FC = () => {
  const { Dragger } = Upload;
  const [loading, setLoading] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [fileList, setFileList] = useState<any>([]);
  const headerUploadRef = useRef(null);
  useEffect(() => {
    document.title = '上传文档'; //设置标题
  }, []);
  const upLoadProps: UploadProps = {
    name: 'file',
    accept: '.docx, .pdf, .doc, .txt',
    action: '',
    headers: {},
    multiple: true,
    maxCount: 10,
    // disabled: fileList.length > 0,
    showUploadList: false,
    beforeUpload: () => {
      // return readFileContent(file);
      return false;
    },
    onChange: async (filer: any) => {
      console.log('==filer=', filer);
      if (filer.file?.status !== 'uploading') {
        const file = filer.file;
        const fileInfo = file.name.split('.');
        file.title = fileInfo[0];
        file.accept = fileInfo[1];
        const files = filer.fileList.map((file: any) => {
          if (file.uid === filer.file.uid) {
            file.originFileObj = filer.file;
          }

          return file;
        });
        setFileList(files);
      }
      if (filer.file?.status === 'done') {
        message.success(`${filer.file.name} file uploaded successfully`);
      } else if (filer.file?.status === 'error') {
        message.error(`${filer.file.name} file upload failed.`);
      }
    },
    style: { height: '500px' },
  };
  const goToUrl = () => {
    history.push('/miniModel2');
  };
  const handleOk = () => {
    setIsModalOpen(false);
    goToUrl();
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    setFileList([]);
    if (headerUploadRef.current) {
      headerUploadRef?.current?.fileList.splice(0);
    }
  };
  //确定上传
  const handleUpload = async () => {
    let newFormData: any = new FormData();
    fileList.forEach((file: any) => {
      newFormData.append(`files`, file.originFileObj, file.originFileObj.name);
    });
    if (fileList.length <= 0) {
      message.warning('请选择要上传的文件');
      return;
    }
    setLoading(true);
    let res = await upload_files(newFormData);
    if (res.code === 0) {
      setIsModalOpen(true);
    } else {
      message.error(res?.msg);
    }
    setLoading(false);
  };

  return (
    <div className="miniModelWrap">
      <div className="uploadMainBox">
        <div className="uploadMainTitle">上传文档至数据处理工具：(最多可上传100个文件)</div>
        <div className="uploadMain">
          <Dragger ref={headerUploadRef} {...upLoadProps}>
            <div className="file-con-sel">
              <p className="ant-upload-drag-icon" style={{ marginTop: '70px', fontSize: '18px' }}>
                <FileAddOutlined />
              </p>
              <p className="ant-upload-text" style={{ marginBottom: '70px', fontSize: '14px' }}>
                直接拖拽文档到此，或点击选择文档
              </p>
            </div>
          </Dragger>
        </div>
      </div>
      <div className="uploadFileWrap">
        <div className="uploadFileTitle">
          <span className="uploadFileTitle-hd">上传文档列表 ({fileList.length})</span>
          <span className="uploadFileTitle-bd">
            <Button loading={loading} type="primary" onClick={handleUpload}>
              确定上传
            </Button>
            <Button disabled={loading} onClick={goToUrl}>
              去清洗文档
            </Button>
          </span>
        </div>
        <div className="uploadFileBox">
          <div style={{ padding: '0 15px' }}>
            {fileList.map((item: any, index: number) => {
              return (
                <div key={index} className="fileCard">
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <img src={DOC_ICON} alt="" width={26} height={26} />
                    <div style={{ marginLeft: '12px' }}>{item?.name.substring(0, 15)}</div>
                    {item?.originFileObj.fileStatus !== 'normal' && (
                      <div style={{ marginLeft: '10px', color: 'red' }}>
                        {item.originFileObj.fileStatus}
                      </div>
                    )}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <img
                      src={DEL_ICON}
                      width={14}
                      height={16}
                      alt=""
                      style={{ cursor: 'pointer' }}
                      onClick={(e) => {
                        e.stopPropagation();
                        const fileListCopy = [...fileList];
                        fileListCopy.splice(index, 1);
                        if (headerUploadRef.current) {
                          headerUploadRef?.current?.fileList.splice(index, 1);
                        }
                        setFileList(fileListCopy);
                      }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <Modal
        title="提示"
        cancelText="继续上传"
        okText="去清洗文档"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>文件上传成功 是否要清洗文档</p>
      </Modal>
    </div>
  );
};
export default MiniModel1;
